package com.hup.vd.presenter;

import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.commons.start.SimpleExitHandler;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.swing.frame.SingletonWindowHelper;
import com.hup.vd.service.TaskService;
import com.hup.vd.service.m3u8.HtmlUrlHandler;
import com.hup.vd.view.AppTray;
import com.hup.vd.view.MainFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author hugan
 * @date 2022/1/11
 */
@Slf4j
@Component
public class MainPresenter {

    private AppTray appTray;

    public MainPresenter() {
        SpringContext.getBean(SimpleExitHandler.class).setExitAction(this::doExit);
    }

    public void startUp() {
        new MainFrame().setVisible(true);
        appTray = new AppTray();
        appTray.doShow();
    }

    private void doExit() {
        if (!SpringContext.getBean(TaskService.class).hasDownloading()) {
            exitNow();
        } else {
            MainFrame mainFrame = SingletonWindowHelper.getWindow(MainFrame.class);
            mainFrame.setVisible(true);
            DialogHelper.yesNo("是否退出?").okAction(this::exitNow).show(mainFrame);
        }
    }

    private void exitNow() {
        log.info("正在退出");
        SpringContext.getBean(SimpleExitHandler.class).setExiting(true);
        MainFrame mainFrame = SingletonWindowHelper.getWindow(MainFrame.class);
        mainFrame.setVisible(false);
        appTray.doHide();
        mainFrame.doInBackground("关闭ChromeDriver", () -> {
            SpringContext.getBean(HtmlUrlHandler.class).destroy();
            System.exit(0);
        });
    }

}
